import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
} from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { ArticleBodyDto } from './artcle.dto';
import { Article as ArticleSchema } from './article.model';

@Controller('article')
@ApiTags('文章模块')
export class ArticleController {
  /**
   * 注入模型
   * @param ArticleSchema // 模型骨架
   * @param ArticleModel // 对象模型
   */
  constructor(
    @InjectModel(ArticleSchema)
    private readonly ArticleModel: ModelType<ArticleSchema>,
  ) {}

  @Get('get')
  @ApiOperation({ summary: '获取文章' })
  async index() {
    return await this.ArticleModel.find();
  }

  @Get('getDetails/:id')
  @ApiOperation({ summary: '获取文章详情' })
  async detail(@Param('id') id: string) {
    return await this.ArticleModel.findById(id);
  }

  @Post('create')
  @ApiOperation({ summary: '创建文章' })
  async create(@Body() data: ArticleBodyDto) {
    await this.ArticleModel.create(data);
    return {
      success: true,
      data,
    };
  }

  @Put('update/:id')
  @ApiOperation({ summary: '更新文章' })
  async update(@Param('id') id: string, @Body() data: ArticleBodyDto) {
    // 找到ID后更新数据
    await this.ArticleModel.findByIdAndUpdate(id, data);
    return {
      success: true,
      data,
    };
  }

  @Delete('delete/:id')
  @ApiOperation({ summary: '删除文章' })
  async remove(@Param('id') id: string) {
    // 找到ID后删除数据
    await this.ArticleModel.findByIdAndDelete(id);
    return { id, success: true };
  }
}
